package com.loiot.baqi.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.loiot.baqi.constant.Const;
import com.loiot.baqi.constant.URLConst;
import com.loiot.baqi.controller.response.AjaxResponse;
import com.loiot.baqi.controller.response.Pager;
import com.loiot.baqi.pojo.TgQqGroup;
import com.loiot.baqi.pojo.TgQqMember;
import com.loiot.baqi.pojo.WeiAccountQqGroup;
import com.loiot.baqi.service.TgQqGroupService;
import com.loiot.baqi.service.TgQqMemberService;
import com.loiot.baqi.service.WeiAccountQqGroupService;
import com.loiot.baqi.status.SubscribeStatus;
import com.loiot.baqi.utils.UserSessionUtils;
import com.loiot.commons.message.util.JsonUtil;
import com.timeloit.pojo.Account;


/**
 * QQ成员 处理器。
 * TgQqMember
 * @author  wangzx 
 * @creation 2016-03-21
 */


@Controller
@RequestMapping(value = "/tgQqMember")
public class TgQqMemberController {
    
    public static final AjaxResponse NUMBER_GROUP_EXIST= new AjaxResponse(-100, "QQ号在该群中已存在");
    
    public static final AjaxResponse GROUP_NOT_ASSIGN= new AjaxResponse(-100, "QQ群还未分配");
    
    private Logger log = LoggerFactory.getLogger(this.getClass());
    
    @Resource
	private TgQqMemberService tgQqMemberService;
    
    @Resource
  	private TgQqGroupService tgQqGroupService;
    
    @Resource
   	private WeiAccountQqGroupService weiAccountQqGroupService;
    
	private TgQqMember tgQqMember;
	
	private HashMap<String,Object> pmap = new HashMap<String,Object>();
	
	/**
     * 跳转  QQ成员列表页
     * 
     * @return 模板位置
     */
    @RequestMapping(value = "/list")
    public String list(@RequestParam(value = "pi", defaultValue = "0") int pageIndex,
    		@RequestParam(value = "jsonParam", defaultValue = "{}") String jsonParam,
    	TgQqMember p, ModelMap model)throws Exception {
    	HashMap<String,Object> paramMap=this.getParaMap(jsonParam, model);
    	paramMap.put("qtype", "like");
		if (p.getQqGroup() != null) {
			paramMap.put("qqGroup", p.getQqGroup());
			TgQqGroup group = tgQqGroupService.getTgQqGroupById(p.getQqGroup());
			model.put("qqGroupNumber", group.getNumber());
		}
    	//用户数据过滤
    	paramMap.put("inPerson", UserSessionUtils.getAccount().getAccountId());
        Pager<TgQqMember> pager = tgQqMemberService.queryTgQqMemberListPage(paramMap , pageIndex);
        model.put("pager", pager);
        model.put("jsonParam", jsonParam);
        return "/tgQqMember/tgQqMember_list";
    }
    
    /**
     * 获取查询条件
     * @param jsonParam
     * @param model
     * @return
     */
    public HashMap<String,Object> getParaMap(String jsonParam,ModelMap model){
    	HashMap<String,Object> newParamMap = newParamMap =  new HashMap<String,Object>();
    	 HashMap<String,Object> paramMap =JsonUtil.toObject(jsonParam, HashMap.class);
		Iterator iter = paramMap.entrySet().iterator();
		while (iter.hasNext()) {
		Map.Entry entry = (Map.Entry) iter.next();
    		Object key = entry.getKey();
    		Object val = entry.getValue();
    		if(key.toString().equals("name")){
    			newParamMap.put("nameT", val);
    		}else
    		if(String.valueOf(val).length()>0){
    			newParamMap.put(String.valueOf(key), val);
        		model.put(String.valueOf(key), val);
    		}
		}
		return newParamMap;
    }

    /**
     * 跳转到添加页面
     * 
     * @return
     */
    @RequestMapping(value = "/toAdd")
    public String toAddTgQqMember(ModelMap model, String qqGroupNumber) {
    	model.put("qqGroupNumber", qqGroupNumber);
        return "/tgQqMember/tgQqMember_add";
    }

    /**
     * 添加  QQ成员
     * 
     * @param p 对象参数
     * @return ajax响应
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object addTgQqMember(TgQqMember p,HttpSession session,HttpServletRequest request) {
    	try {
            Account account = (Account) session.getAttribute(Const.SESSION_USER_KEY);
    		//验证群号是否有效
            pmap.clear();
            pmap.put("number", p.getQqGroupNumber());
            TgQqGroup group = tgQqGroupService.getTgQqGroup(pmap);
            if(group == null){
		        return GROUP_NOT_ASSIGN;
			}
            //验证QQ号+QQ群是否已存在
            pmap.clear();
            pmap.put("number", p.getNumber());
            pmap.put("qqGroup", group.getId());
        	int result=tgQqMemberService.getTgQqMemberListCount(pmap);
        	if(result > 0){
		        return NUMBER_GROUP_EXIST;
			}
        	p.setQqGroup(group.getId());
        	p.setSubscribeStatus(SubscribeStatus.SUBSCRIBED.getCode());
        	p.setInTime(new Date());
        	p.setInPerson(account.getAccountId());
    		tgQqMemberService.addTgQqMember(p);
    		// 添加成功
    		return AjaxResponse.OK(p.getQqGroup());
    	}
        catch (Exception e) {
			e.printStackTrace();
			 //失败
	        return AjaxResponse.FAILED;
		}
       
    }

    /**
     * 跳转到编辑页面
     * 
     * @return
     */
    @RequestMapping(value = "/toEdit")
    public String toEditTgQqMember(@RequestParam(value = "id", required = true) java.lang.Long id, ModelMap model)throws Exception {
    	if(id==null){
    		return URLConst.ERROR_URL;
    	}
    	model.put("pid",  id);
        return "/tgQqMember/tgQqMember_add";
    }

    /**
     * 更新 QQ成员
     * <p>
     * 前台onlyName传值格式：QQ号_QQ群号
     * @param p 对象参数
     * @return ajax响应
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
	public Object editTgQqMember(TgQqMember p, HttpSession session,
			HttpServletRequest request) {
		try {
			// 获得账号
			// Account account = (Account)
			// session.getAttribute(Const.SESSION_USER_KEY);
			// 如果前端，没有改变编号，就不用验证
			String onlyQqGroupNumber = request.getParameter("onlyQqGroupNumber");
			String onlyNumber = request.getParameter("onlyNumber");
			String onlyQqGroup = request.getParameter("onlyQqGroup");
			long groupId = Long.valueOf(onlyQqGroup);
			// 如果群号改变了，则需验证
			if (!onlyQqGroupNumber.equals(p.getQqGroupNumber())) {
				pmap.clear();
				pmap.put("groupNumber", p.getQqGroupNumber());
				WeiAccountQqGroup group = weiAccountQqGroupService.getWeiAccountQqGroup(pmap);
				if (group == null) {
					return GROUP_NOT_ASSIGN;
				}
				groupId = group.getGroupId();
			}
			p.setQqGroup(groupId);

			// 如果QQ号+QQ群改变了，则需验证
			if (!onlyNumber.equals(p.getNumber())
					|| Long.valueOf(onlyQqGroup) != groupId) {
				pmap.clear();
				pmap.put("number", p.getNumber());
				pmap.put("qqGroup", groupId);
				int result = tgQqMemberService.getTgQqMemberListCount(pmap);
				if (result > 0) {
					return NUMBER_GROUP_EXIST;
				}
			}
			tgQqMemberService.updateTgQqMember(p);
			// 添加成功
    		return AjaxResponse.OK(p.getQqGroup());
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResponse.FAILED;
		}
	}

    /**
     * 跳转到查看页面
     * 
     * @return
     */
    @RequestMapping(value = "/toView")
    public String toViewTgQqMember(@RequestParam(value = "id", required = true) java.lang.Long id, ModelMap model)throws Exception {
    	if(id==null){
    		return URLConst.ERROR_URL;
    	}
    	//model.put("p", tgQqMemberService.getTgQqMemberById(id));
    	 model.put("pid",  id);
    	return "/tgQqMember/tgQqMember_add";
    }

    /**
     * 批量删除  QQ成员
     * 
     * @param id TgQqMemberID
     */
    @RequestMapping(value = "/delete")
    public String deleteTgQqMember(@RequestParam(value = "ids", required = true) String ids,HttpServletRequest request)throws Exception {
		TgQqMember p = new TgQqMember();
		p.setIds(ids == null ? new String[0] : ids.split(","));
		tgQqMemberService.deleteTgQqMember(p);
        String s = request.getHeader("Referer");
        String redirectStr = s.substring(s.indexOf("/tgQqMember/"), s.length());
        return "redirect:"+redirectStr;
    }
    
    /**
     * ajax批量删除  QQ成员
     * 
     * @param id TgQqMemberID
     */
    @RequestMapping(value = "/ajaxDelete")
    @ResponseBody
    public Object ajaxDeleteTgQqMember(@RequestParam(value = "ids", required = true) String ids) {
    	try {
			TgQqMember p = new TgQqMember();
			p.setIds(ids == null ? new String[0] : ids.split(","));
			tgQqMemberService.deleteTgQqMember(p);
			return AjaxResponse.OK;
    	} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		  return AjaxResponse.FAILED;
		}
    }
    
    /**
     * ajax 根据id查询实体bean
     * @return
     */
    @RequestMapping(value = "/getById")
    @ResponseBody
    public Object ajaxGetById(@RequestParam(value = "id", required = true) java.lang.Long id)throws Exception {
    	TgQqMember p = tgQqMemberService.getTgQqMemberById(id);
     	//用户数据过滤
     	/*if(UserSessionUtils.getAccountType()==AccountType.HR.getCode() || UserSessionUtils.getAccountType()==AccountType.JOB_HUNTER.getCode() ){
     		  p = tgQqMemberService.getTgQqMemberById(id, UserSessionUtils.getAccount().getAccountId());
     	} else {
   		      p = tgQqMemberService.getTgQqMemberById(id);
     	}*/
     	if(p==null){
     		return AjaxResponse.NOEXITS;
     	}
    	return AjaxResponse.OK(p);
    }
    
    /**
     * 根据QQ群号查询QQ群是否存在，验证唯一性
     * @return
     * @throws Exception 
     */
    @RequestMapping(value = "/checkQqGroupExits")
    @ResponseBody
	public Object checkQqGroupExits(
			@RequestParam(value = "name", required = true) java.lang.String name,
			@RequestParam(value = "oldname", required = false) java.lang.String oldName,
			@RequestParam(value = "flag", required = true) String flag)
			throws Exception {
		if ("edit".equals(flag) && oldName.equals(name)) {
			return AjaxResponse.OK(null);
		}
		// 验证唯一性
		pmap.clear();
		pmap.put("number", name);
		int result = tgQqGroupService.getTgQqGroupListCount(pmap);
		if (result < 1) {
			return GROUP_NOT_ASSIGN;
		}
		return AjaxResponse.OK(null);
	}
}
